#include "common.h"
#include "ddraw.h"
#include "ddraw_fwd.h"
#include "d3d.h"
#include "MyDirectDraw.h"
#pragma comment(lib, "d3dx.lib")

#pragma pack(1)

static HINSTANCE hLThis = 0;
static HINSTANCE hDDRAW = 0;

static HRESULT (WINAPI *DirectDrawCreateEx_t)(GUID FAR * lpGuid, LPVOID  *lplpDD, REFIID  iid,IUnknown FAR *pUnkOuter);

extern "C" HRESULT WINAPI HookedDirectDrawCreateEx(GUID FAR * lpGuid, LPVOID  *lplpDD, REFIID  iid,IUnknown FAR *pUnkOuter) {
    HRESULT hr = DirectDrawCreateEx_t(lpGuid, lplpDD, iid, pUnkOuter);
    if (!SUCCEEDED(hr)) {
        return hr;
    }

    *lplpDD = new MyDirectDraw((IDirectDraw7*)*lplpDD);
    return hr;
};

BOOL WINAPI DllMain(HINSTANCE hInst, DWORD reason, LPVOID) {
    if (reason == DLL_PROCESS_ATTACH) {
        DebugWrite("DDRAW Proxy DLL starting.\n");
        hLThis = hInst;

        hDDRAW = LoadLibrary( "ddraw_" );
        if (!hDDRAW) {
            return FALSE;
        }

        *(void**)&DirectDrawCreateEx_t = (void*)GetProcAddress(hDDRAW, "DirectDrawCreateEx");
    } else if (reason == DLL_PROCESS_DETACH) {
        FreeLibrary(hDDRAW);
        DebugWrite("DDRAW Proxy DLL signing off.\n");
    }
    return TRUE;
};